package com.xjscrm.console.service.customer.chat;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.console.common.util.LoginContext;
import com.xjscrm.console.dto.chat.ChatWordsLibraryOptDTO;
import com.xjscrm.console.dto.chat.ChatWordsLibraryOrderDTO;
import com.xjscrm.console.dto.chat.ChatWordsLibraryQueryDTO;
import com.xjscrm.console.dto.chat.ChatWordsLibraryUploadDTO;
import com.xjscrm.console.entity.ChatWordsLibrary;
import com.xjscrm.console.entity.ChatWordsLibraryGroup;
import com.xjscrm.console.mapper.ChatWordsLibraryGroupMapper;
import com.xjscrm.console.mapper.ChatWordsLibraryMapper;
import com.xjscrm.console.vo.LoginVO;
import com.xjscrm.console.vo.chat.ChatWordsLibraryVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author mingyang.chen create in 2024/3/15 11:59
 */
@Service
public class ChatWordsLibraryService {

    @Resource
    private ChatWordsLibraryMapper chatWordsLibraryMapper;
    @Autowired
    private ChatWordsLibraryGroupService chatWordsLibraryGroupService;
    @Autowired
    private ChatWordsLibraryGroupMapper chatWordsLibraryGroupMapper;


    public int deleteByPrimaryKey(Long id) {
        return chatWordsLibraryMapper.deleteByPrimaryKey(id);
    }


    public int insertSelective(ChatWordsLibrary record) {
        return chatWordsLibraryMapper.insertSelective(record);
    }


    public ChatWordsLibrary selectByPrimaryKey(Long id) {
        return chatWordsLibraryMapper.selectByPrimaryKey(id);
    }


    public int updateByPrimaryKeySelective(ChatWordsLibrary record) {
        return chatWordsLibraryMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 分页查询
     *
     * @param login 登录用户
     * @param query 查询参数
     * @return
     */
    public List<ChatWordsLibraryVO> search(LoginVO login, ChatWordsLibraryQueryDTO query) {


        List<ChatWordsLibrary> wordsLibraryList = chatWordsLibraryMapper.query(login.getMerId(), login.getId(), query);

        if (ObjectUtils.isEmpty(wordsLibraryList)) {
            return Lists.newArrayList();
        }
        List<Long> groupIds = wordsLibraryList.stream().map(ChatWordsLibrary::getGroupId).distinct().collect(Collectors.toList());
        List<ChatWordsLibraryGroup> groups = chatWordsLibraryGroupMapper.selectByIds(login.getMerId(), groupIds);
        if (Objects.isNull(groups)) {
            groups = new ArrayList<>();
        }
        Map<Long, String> collect = groups.stream().collect(Collectors.toMap(ChatWordsLibraryGroup::getId, ChatWordsLibraryGroup::getName));
        //
        List<ChatWordsLibraryVO> records = wordsLibraryList.stream().map(item -> {
            ChatWordsLibraryVO chatWordsLibraryVO = new ChatWordsLibraryVO();
            BeanUtils.copyProperties(item, chatWordsLibraryVO);
            if (collect.containsKey(item.getGroupId())) {
                chatWordsLibraryVO.setGroupName(collect.get(item.getGroupId()));
            }
            if (StringUtils.isNotBlank(item.getContent())) {
                List<MsgData> contents = JSON.parseArray(item.getContent(), MsgData.class);
                chatWordsLibraryVO.setContent(contents);
            }
            return chatWordsLibraryVO;
        }).collect(Collectors.toList());

        return records;
    }

    public void add(LoginVO login, ChatWordsLibraryOptDTO opt) {
        ChatWordsLibraryGroup chatWordsLibraryGroup = chatWordsLibraryGroupMapper.selectByPrimaryKey(opt.getGroupId());
        if (Objects.isNull(chatWordsLibraryGroup)) {
            throw new BusinessException("话术分组不存在");
        }
        if (!Objects.equals(chatWordsLibraryGroup.getType(), opt.getType())) {
            throw new BusinessException("话术分组的类型和话术类型不匹配");
        }
        Integer sort = chatWordsLibraryMapper.selectMaxSort(login.getMerId(), login.getId());
        ChatWordsLibrary chatWordsLibrary = new ChatWordsLibrary();
        BeanUtils.copyProperties(opt, chatWordsLibrary);
        chatWordsLibrary.setId(IdUtil.getSnowflakeNextId());
        chatWordsLibrary.setStaffId(login.getId());
        chatWordsLibrary.setMerId(login.getMerId());
        chatWordsLibrary.setCreateBy(login.getId());
        chatWordsLibrary.setSort(Objects.isNull(sort) ? 0 : sort + 1);
        chatWordsLibrary.setCreateTime((int) (System.currentTimeMillis() / 1000L));
        chatWordsLibrary.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
        chatWordsLibrary.setUpdateBy(login.getId());

        chatWordsLibraryMapper.insertSelective(chatWordsLibrary);
    }

    public void edit(LoginVO login, ChatWordsLibraryOptDTO opt) {
        ChatWordsLibrary chatWordsLibrary = chatWordsLibraryMapper.selectByPrimaryKey(opt.getId());
        if (Objects.isNull(chatWordsLibrary)) {
            throw new BusinessException("话术不存在");
        }
        Long groupId = Objects.nonNull(opt.getGroupId()) ? opt.getGroupId() : chatWordsLibrary.getGroupId();
        //
        ChatWordsLibraryGroup chatWordsLibraryGroup = chatWordsLibraryGroupMapper.selectByPrimaryKey(groupId);
        if (Objects.isNull(chatWordsLibraryGroup)) {
            throw new BusinessException("话术分组不存在");
        }
        if (Objects.nonNull(opt.getType()) && !Objects.equals(chatWordsLibraryGroup.getType(), opt.getType())) {
            throw new BusinessException("话术分组的类型和话术类型不匹配");
        }
        ChatWordsLibrary edit = new ChatWordsLibrary();
        BeanUtils.copyProperties(opt, edit);
        edit.setId(opt.getId());
        edit.setUpdateBy(login.getId());
        edit.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
        chatWordsLibraryMapper.updateByPrimaryKeySelective(edit);
    }

    public void delete(LoginVO login, Long id) {
        chatWordsLibraryMapper.deleteByPrimaryKey(id);
    }

    public Object sort(LoginVO login, ChatWordsLibraryOrderDTO opt) {

        for (ChatWordsLibraryOrderDTO.Item item : opt.getSortItems()) {
            ChatWordsLibrary exits = chatWordsLibraryMapper.selectById(login.getMerId(), item.getId());
            if (Objects.isNull(exits)) {
                continue;
            }
            ChatWordsLibrary update = new ChatWordsLibrary();
            update.setId(item.getId());
            update.setSort(item.getSort());
            update.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
            chatWordsLibraryMapper.updateByPrimaryKeySelective(update);
        }
        return null;
    }

    public Object get(@MerId Long merId, Long id) {

        ChatWordsLibrary chatWordsLibrary = chatWordsLibraryMapper.selectById(merId, id);
        ChatWordsLibraryVO chatWordsLibraryVO = new ChatWordsLibraryVO();
        BeanUtils.copyProperties(chatWordsLibrary, chatWordsLibraryVO);
        Long groupId = chatWordsLibrary.getGroupId();

        ChatWordsLibraryGroup chatWordsLibraryGroup = chatWordsLibraryGroupMapper.selectById(merId, groupId);
        if (Objects.nonNull(chatWordsLibraryGroup)) {
            chatWordsLibraryVO.setGroupName(chatWordsLibraryGroup.getName());
        }
        if (StringUtils.isNotBlank(chatWordsLibrary.getContent())) {
            List<MsgData> contents = JSON.parseArray(chatWordsLibrary.getContent(), MsgData.class);
            chatWordsLibraryVO.setContent(contents);
        }
        return chatWordsLibraryVO;
    }

    @Transactional
    public void save(@MerId Long merId, Integer type, List<ChatWordsLibraryUploadDTO> chatWordsLibraryList) {
        if (ObjectUtils.isEmpty(chatWordsLibraryList)) {
            return;
        }
        LoginVO login = LoginContext.getLogin();
        Map<String, List<ChatWordsLibraryUploadDTO>> groupNameCache = chatWordsLibraryList.stream().collect(Collectors.groupingBy(ChatWordsLibraryUploadDTO::getGroupName));

        for (Map.Entry<String, List<ChatWordsLibraryUploadDTO>> itemEntry : groupNameCache.entrySet()) {
            String groupName = StringUtils.defaultIfBlank(itemEntry.getKey(), "未分组");
            List<ChatWordsLibraryUploadDTO> words = itemEntry.getValue();

            ChatWordsLibraryGroup chatWordsLibraryGroup = chatWordsLibraryGroupService.getByNameIfAbsentAdd(merId, type, groupName);
            Long groupId = chatWordsLibraryGroup.getId();

            for (ChatWordsLibraryUploadDTO item : words) {
                if (StringUtils.isAnyBlank(item.getContent(), item.getTitle())) {
                    continue;
                }
                String[] content = item.getContent().split("\n");

                List<JSONObject> contentList = new ArrayList<>(content.length);
                for (String s : content) {
                    JSONObject contentItem = new JSONObject();
                    contentItem.put("content", s);
                    contentItem.put("msgType", 1);
                    contentList.add(contentItem);
                }
                String contentJson = JSON.toJSONString(contentList);
                Integer sort = chatWordsLibraryMapper.selectMaxSort(merId, login.getId());
                ChatWordsLibrary chatWordsLibrary = new ChatWordsLibrary();
                chatWordsLibrary.setId(IdUtil.getSnowflakeNextId());
                chatWordsLibrary.setStaffId(login.getId());
                chatWordsLibrary.setMerId(login.getMerId());
                chatWordsLibrary.setTitle(item.getTitle());
                chatWordsLibrary.setGroupId(groupId);
                chatWordsLibrary.setType(type);
                chatWordsLibrary.setContent(contentJson);
                chatWordsLibrary.setContentDesc(StringUtils.join(content, "+"));
                chatWordsLibrary.setContentType(1);
                chatWordsLibrary.setCreateBy(login.getId());
                chatWordsLibrary.setSort(Objects.isNull(sort) ? 0 : sort + 1);
                chatWordsLibrary.setCreateTime((int) (System.currentTimeMillis() / 1000L));
                chatWordsLibrary.setUpdateTime((int) (System.currentTimeMillis() / 1000L));
                chatWordsLibrary.setUpdateBy(login.getId());

                chatWordsLibraryMapper.insertSelective(chatWordsLibrary);
            }
        }
    }
}
